package com.xbniao.owms.utils.QRCode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * 类说明
 * @author wangbin
 */
public class BuildQRCode {
	
	// 初始化pdf的一些字体
	private static Font fontsize6 = FontFactory.getFont(BaseFont.HELVETICA, BaseFont.WINANSI, 6);
	private static Font fontsize7 = FontFactory.getFont(BaseFont.HELVETICA, BaseFont.WINANSI, 7);
	private static Font fontsize7_blod = FontFactory.getFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, 7);
	private static Font fontsize9 = FontFactory.getFont(BaseFont.HELVETICA, BaseFont.WINANSI, 9);
	private static Font fontsize90 = FontFactory.getFont(BaseFont.HELVETICA, BaseFont.WINANSI,90);
	// 自定义pdf纸张的大小尺寸
	private static RectangleReadOnly rr = new RectangleReadOnly(154,196);
	// 初始化固定的app地址
	private static String app_url = "http://trace.xbniao.com/dist/view/r.html";
	// 初始化固定的app地址的byte[]
	private static byte[] app_byte = null;
	static {
		try {
			app_byte = QRCodeUtil.decodeToByte(app_url);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	   * 生成二维码
	   * @param template
	   * @param barCodeList
	   */
	 public static void createQRTemplate(List<QRCodeDTO> list,String localPath){
	 	  Document document = new Document(rr,0f,0f,7f,0f);
	 	  //支持中文
	 	  PdfPTable mainTable = new PdfPTable(1);   
	 	  mainTable.setTotalWidth(141.73f);
	 	  mainTable.setLockedWidth(true);
	 	  setPdfPTableBoder(mainTable);
	 	  mainTable.setHorizontalAlignment(Element.ALIGN_CENTER);
	      try { 
		      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(localPath)); 
		      document.open();
		      writer.getDirectContent();
		      
		      for(QRCodeDTO dto : list){
		    	  // 建立上半部分的table
		    	  PdfPTable topTable = createBarTableTop(dto.getUrl(),dto.getTraceCode());
		    	  // 建立skutable
		    	  PdfPTable skuTable = createBarTableTop(dto.getSku());
			 	  // 建立下半部分的table
		    	  PdfPTable bottomTable = createBarTableBottom();
		    	  for(int i = 0 ; i < dto.getPrintCount(); i++)
		    	  {
			    	  // 将上下两部分table设置到主table中
			    	  mainTable.addCell(topTable);
			    	  mainTable.addCell(skuTable);
			    	  mainTable.addCell(bottomTable);
		    	  }
		      }
		      document.add(mainTable); 
		      document.close();
	      } catch (Exception de) {       
	    	  de.printStackTrace(); 
	      }
	 }
	 
	 /**
	   * 下载二维码
	   * @param template
	   * @param barCodeList
	   */
	 public static void downQRTemplate(List<QRCodeDTO> list,OutputStream out){
	 	  Document document = new Document(rr,0f,0f,7f,0f);
	 	  //支持中文
	 	  PdfPTable mainTable = new PdfPTable(1);   
	 	  mainTable.setTotalWidth(141.73f);
	 	  mainTable.setLockedWidth(true);
	 	  setPdfPTableBoder(mainTable);
	 	  mainTable.setHorizontalAlignment(Element.ALIGN_CENTER);
	      try { 
		      PdfWriter writer = PdfWriter.getInstance(document, out); 
		      document.open();
		      writer.getDirectContent();
		      for(QRCodeDTO dto : list){
		    	  // 建立上半部分的table
		    	  PdfPTable topTable = createBarTableTop(dto.getUrl(),dto.getTraceCode());
		    	  // 建立skutable
		    	  PdfPTable skuTable = createBarTableTop(dto.getSku());
			 	  // 建立下半部分的table
		    	  PdfPTable bottomTable = createBarTableBottom();
		    	  for(int i = 0 ; i < dto.getPrintCount() ; i++)
		    	  {
			    	  // 将上下两部分table设置到主table中
			    	  mainTable.addCell(topTable);
			    	  mainTable.addCell(skuTable);
			    	  mainTable.addCell(bottomTable);
		    	  }
		      }
		      document.add(mainTable); 
		      document.close();
	      } catch (Exception de) {       
	    	  de.printStackTrace(); 
	      }
	 }
	 
	 private static void setPdfPTableBoder(PdfPTable table)
	 {
		 table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
		 table.getDefaultCell().setBorderWidth(0f);
		 table.getDefaultCell().setPadding(0f);    // 设置此值是为了table内部不会产生多余的空隙
	 }
	 
	 /**
	  * 建立上半部分的table
	  * @return
	  * @throws DocumentException
	  * @throws IOException
	  */
	 private static PdfPTable createBarTableTop(String url,String traceCode) throws DocumentException, IOException{
		 /**建立顶部文字的PdfPTable   start**/
		 PdfPTable bartableTop = new PdfPTable(1);
		 setPdfPTableBoder(bartableTop);
		 Paragraph graph11 = new Paragraph("IMPORT  AND  EXPORT  COMMODITY",fontsize7_blod);
		 PdfPCell cell11 = createPdfCell(graph11,Element.ALIGN_TOP, Element.ALIGN_CENTER, true);
		 bartableTop.addCell(cell11);
		 
		 Paragraph graph12 = new Paragraph("TRACING",fontsize7_blod);
		 PdfPCell cell12 = createPdfCell(graph12,Element.ALIGN_TOP, Element.ALIGN_CENTER, true);
		 bartableTop.addCell(cell12);
		 /**建立顶部文字的PdfPTable   end**/
		 
		 /**建立中部大中括号和二维码还有二维码下方码的的PdfPTable   start**/
		 float[] widths1 = {0.205f, 0.59f, 0.205f};
		 PdfPTable bartableMid = new PdfPTable(widths1);
		 setPdfPTableBoder(bartableMid);
		 Paragraph graph21 = new Paragraph("[",fontsize90);
		 PdfPCell cell21 = createPdfCell(graph21,Element.ALIGN_TOP, Element.ALIGN_RIGHT, true);
		 cell21.setFixedHeight(92f);
		 bartableMid.addCell(cell21);
		 
		 //  二维码和二维码下方数字的table  start
		 PdfPTable bartableMidmag = new PdfPTable(1);
		 setPdfPTableBoder(bartableMidmag);
		 PdfPCell cell221 = createQRCodePDFCell(url); 
		 cell221.setFixedHeight(80f);
		 cell221.setVerticalAlignment(Element.ALIGN_BOTTOM);
		 cell221.setHorizontalAlignment(Element.ALIGN_CENTER);
		 cell221.setUseAscender(true);
		 cell221.setUseDescender(true);
		 cell221.setBorder(PdfPCell.NO_BORDER);
		 bartableMidmag.addCell(cell221);
		 
		 Paragraph graph222 = new Paragraph(hexToInteger(traceCode),fontsize9);
		 PdfPCell cell222 = createPdfCell(graph222,Element.ALIGN_TOP, Element.ALIGN_CENTER, true);
		 cell222.setPaddingTop(-2f);
		 bartableMidmag.addCell(cell222);
		 
		 bartableMid.addCell(bartableMidmag);
		 //  二维码和二维码下方数字的table  end
		 
		 Paragraph graph23 = new Paragraph("]",fontsize90);
		 PdfPCell cell23 = createPdfCell(graph23,Element.ALIGN_TOP, Element.ALIGN_RIGHT, true);
		 cell23.setFixedHeight(92f);
		 bartableMid.addCell(cell23);
		 /**建立中部大中括号和二维码还有二维码下方码的的PdfPTable   end**/
		 
		 /**建立下方文字的PdfPTable   start**/
		 PdfPTable bartableBottom = new PdfPTable(1);
		 setPdfPTableBoder(bartableBottom);
		 
		 Paragraph graph31 = new Paragraph("CHINA ENTRY-EXIT INSPECTION AND",fontsize7);
		 PdfPCell cell31 = createPdfCell(graph31,Element.ALIGN_TOP, Element.ALIGN_CENTER, true);
		 cell31.setPaddingTop(-2f);
		 bartableBottom.addCell(cell31);
		 
		 Paragraph graph32 = new Paragraph("QUARANTINE (Beijing)",fontsize7);
		 PdfPCell cell32 = createPdfCell(graph32,Element.ALIGN_TOP, Element.ALIGN_CENTER, false);
		 cell32.setPaddingBottom(3f);
		 bartableBottom.addCell(cell32);
		 /**建立下方文字的PdfPTable   end**/
		 
		 /**建立整体的PdfPTable   start**/
		 PdfPTable bartableWhole = new PdfPTable(1);
		 setPdfPTableBoder(bartableWhole);
		 bartableWhole.addCell(bartableTop);
		 bartableWhole.addCell(bartableMid);
		 bartableWhole.addCell(bartableBottom);
		 /**建立整体的PdfPTable   end**/
		 
		 return bartableWhole;
	 }
	 
	 /**
	  * 建立sku的table
	  * @param sku
	  * @return
	  * @throws DocumentException
	  * @throws IOException
	  */
	 private static PdfPTable createBarTableTop(String sku) throws DocumentException, IOException
	 {
		 PdfPTable bartableTop = new PdfPTable(1);
		 setPdfPTableBoder(bartableTop);
		 
		 Paragraph graph31 = new Paragraph(sku,fontsize7);
		 PdfPCell cell31 = createPdfCell(graph31,Element.ALIGN_BOTTOM, Element.ALIGN_CENTER, true);
		 cell31.setPaddingTop(6f);
		 cell31.setFixedHeight(14f);
		 bartableTop.addCell(cell31);
		 
		 return bartableTop;
	 }
	 
	 /**
	  * 建立下半部分的table
	  * @return
	  * @throws DocumentException
	  * @throws IOException
	  */
	 private static PdfPTable createBarTableBottom() throws DocumentException, IOException{
		 
		 /**建立整体的PdfPTable   start**/
		 float[] widths1 = {0.65f, 0.35f};
		 PdfPTable bartableWhole = new PdfPTable(widths1);
		 setPdfPTableBoder(bartableWhole);
		 /**建立整体的PdfPTable   end**/
		 
		 /**建立左边文字的 PdfPTable    start**/
		 PdfPTable bartableLeft = new PdfPTable(1);
		 setPdfPTableBoder(bartableLeft);
		 
		 Paragraph graph32 = new Paragraph("Use the \"Traceability\" APP to scan the above QR code to view product traceability information",fontsize6);
		 PdfPCell cell32 = createPdfCell(graph32,Element.ALIGN_TOP, Element.ALIGN_LEFT, true);
		 cell32.setFixedHeight(23f);
		 bartableLeft.addCell(cell32);
		 
		 Paragraph graph33 = new Paragraph("Scan the QR code on the right to download the \"Traceability\" APP",fontsize6);
		 PdfPCell cell33 = createPdfCell(graph33,Element.ALIGN_BOTTOM, Element.ALIGN_LEFT, true);
		 cell33.setFixedHeight(17f);
		 bartableLeft.addCell(cell33);
		 /**建立左边文字的 PdfPTable    end**/
		 
		 /**建立右边二维码的 PdfPTable    start**/
		 PdfPTable bartableRight = new PdfPTable(1);
		 setPdfPTableBoder(bartableRight);
		 
		 PdfPCell cell321 = createLocalPDFCell();
		 cell321.setFixedHeight(43f);
		 cell321.setVerticalAlignment(Element.ALIGN_MIDDLE);
		 cell321.setHorizontalAlignment(Element.ALIGN_RIGHT);
		 cell321.setUseAscender(true);
		 cell321.setUseDescender(true);
		 cell321.setBorder(PdfPCell.NO_BORDER);
		 cell321.setPaddingTop(2f);
		 bartableRight.addCell(cell321);
		 /**建立右边二维码的 PdfPTable    end**/
		 
		 bartableWhole.addCell(bartableLeft);
		 bartableWhole.addCell(bartableRight);
		 
		 return bartableWhole;
	 }
	 
	 /**
	 * 生成Cell的基本方法，要想打印边线，在此方法设置即可
	 * @param graph
	 * @param align
	 * @param isHideAllBorders
	 * @return
	 */
	public static PdfPCell createPdfCell (Paragraph graph,int vlign,int align, boolean isHideAllBorders){
		PdfPCell msgGcell = new PdfPCell(graph);
		msgGcell.setVerticalAlignment(vlign);
		msgGcell.setHorizontalAlignment(align);
		msgGcell.setUseAscender(true);
		msgGcell.setUseDescender(true);
		if (isHideAllBorders)
			msgGcell.setBorder(PdfPCell.NO_BORDER);
		else
			setHideTopLeftRigthBorders(msgGcell);
		return msgGcell;
    }
	
	/**
	 * 保留cell的底部边框
	 * @param cell
	 */
	public static void setHideTopLeftRigthBorders(PdfPCell cell)
	{
		cell.disableBorderSide(1);
		cell.disableBorderSide(4);
		cell.disableBorderSide(8);
	}
	
	/**
	 * 将追溯码转换成10位数字标识
	 * @param traceCode
	 * @return
	 */
	public static String hexToInteger(String traceCode)
	{
		String hexnum = traceCode.substring(12, 20);
		String intnum = Integer.parseInt(hexnum, 16)+"";
		int numsize = intnum.length();
		String returnStr = "";
		for(int i = 0 ; i < 10-numsize ; i++)
		{
			returnStr += "0 ";
		}
		char[] chars = intnum.toCharArray();
		for(char cha : chars)
			returnStr += cha + " ";
		return returnStr.substring(0, returnStr.length()-1);
	}
	 
	 /**
	  * 生成二维码的PdfPCell
	  * @param url
	  * @return
	  */
	 private static PdfPCell createQRCodePDFCell(String url)
	 {
		  Image img = null;
		  byte[] imgb = null;
		  try {
			  imgb = QRCodeUtil.decodeToByte(url);
			  img = Image.getInstance(imgb);
		  } catch (Exception e) {
			  e.printStackTrace();
		  }
	      PdfPCell barcodeCell = new PdfPCell(img,true);
	      barcodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	      return barcodeCell;
	 }
	 
	 /**
	  * 生成二维码的PdfPCell
	  * @param barCode
	  * @param param
	  * @param cb
	  * @return
	  */
	 private static PdfPCell createLocalPDFCell()
	 {
		  Image img = null;
		  try {
			  img = Image.getInstance(app_byte);
		  } catch (Exception e) {
			  e.printStackTrace();
		  }
	      PdfPCell barcodeCell = new PdfPCell(img,true);
	      barcodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	      return barcodeCell;
	 }
	 
	public static void main(String[] args) throws DocumentException, IOException {
		 String localPath = "f:/pdf/20170911/9"+File.separator+UUID.randomUUID().toString()+".pdf";
		 
		 List<QRCodeDTO> list = new ArrayList<QRCodeDTO>();
		 QRCodeDTO dto1 = new QRCodeDTO();
		 dto1.setSku("A000173-LM300Router");
		 dto1.setUrl("http://trace.xbniao.com/dist/view/detail.html?traceCode=0010e71316a20000000e732c9866&expressCode=LW263509753CN");
		 dto1.setPrintCount(1);
		 dto1.setTraceCode("0010e71316a20000000e732c9866");
		 
		 /*QRCodeDTO dto2 = new QRCodeDTO();
		 dto2.setSku("A000128-HUWAIBAOBAO012345678");
		 dto2.setUrl("http://www.qq.com");
		 dto2.setPrintCount(1);
		 dto2.setTraceCode("062027410bf200000005a0e3a795");*/
		 
		 list.add(dto1);
		 //list.add(dto2);
		 createQRTemplate(list,localPath);
	}
}
